<template>
  <div v-if="!props.multiply">
    <div v-if="!inputFileData" class="input-picture" @click="inputPicture">
      <el-icon v-if="!props.customIcon" :size="80" color="#3f9eff"
        ><PictureFilled
      /></el-icon>
      <slot></slot>
    </div>
    <div v-else class="input-area">
      <img width="100" height="100" style="color: #7199cb" :src="toWindowUrl" />
      <span class="buts">
        <el-icon :size="25" color="#ffffff" @click.stop="previewPic"
          ><ZoomIn
        /></el-icon>
        <el-icon :size="25" color="red" @click.stop="deletePic"
          ><Delete
        /></el-icon>
      </span>
    </div>
  </div>
  <div v-else>
    <el-card>
      <div class="image-list">
        <div
          v-for="(image, index) in images"
          :key="image.id"
          class="image-container"
        >
          <img :src="image.url" alt="" />
          <el-icon @click="deleteMulPic(index)" size="1.5rem" color="red"
            ><Delete
          /></el-icon>
        </div>
        <div
          v-if="images.length < 9"
          class="input-picture"
          @click="inputPicture"
        >
          <div v-if="!props.customIcon" class="input-entry">
            <el-icon class="circle-plus" color="#4aa3f0"><Plus /></el-icon>
          </div>
          <slot></slot>
        </div>
      </div>
    </el-card>
    <el-button
      v-if="!customUpload"
      style="margin-top: 1rem"
      type="primary"
      :disabled="!fileList.length"
      @click="uploadImages"
      >确认上传</el-button
    >
  </div>
  <el-dialog v-model="dialogVisible">
    <img w-full :src="toWindowUrl" alt="Preview Image" />
  </el-dialog>
</template>
<script setup lang="ts">
import { uploadImageToOss } from "@/utils/tools";
import { ElNotification } from "element-plus";
import { ref } from "vue";

const props = defineProps({
  customIcon: {
    type: Boolean,
    default: false,
  },
  multiply: {
    type: Boolean,
    default: false,
  },
  maxSize: {
    type: Number,
    default: 2048000, // 2M
  },
  type: {
    type: Number,
    default: 0,
  },
  customUpload: {
    type: Boolean,
    default: false
  }
});
interface ImageType {
  id: string;
  url: string;
}
const inputFileData = ref<File|null>(null);
const toWindowUrl = ref<string>("");
const dialogVisible = ref<boolean>(false);
// multipy
const images = ref<ImageType[]>([]);
const previewList = ref<string[]>([]);
const fileList = ref<File[]>([]);

const emit = defineEmits(["upload-success"]);

// const inputPicture = () => {
//   let inputFile = document.createElement("input");
//   inputFile.type = "file";
//   inputFile.accept = "image/*";
//   inputFile.multiple = props.multiply;
//   inputFile.onchange = () => {
//     const file = inputFile.files && inputFile.files[0];
//     if (file?.size > 2048000) {
//       return ElNotification.warning({
//         title: "Warning",
//         message: "图片不能大于2M",
//         offset: 100,
//       });
//     }
//     inputFileData.value = inputFile?.files?.[0] || null;
//     const windowURL = window.URL || window.webkitURL; // 兼容操作
//     toWindowUrl.value = windowURL.createObjectURL(inputFile?.files?.[0]);
//     // console.log(inputFileData.value);
//     emit("upload-success", inputFileData.value);
//     setTimeout(() => {
//       inputFile = null;
//     }, 200);
//   };
//   inputFile.click();
// };

const inputPicture = () => {
  let inputFile:any = document.createElement("input");
  inputFile.type = "file";
  inputFile.accept = "image/*";
  inputFile.multiple = props.multiply;
  const windowURL = window.URL || window.webkitURL; // 兼容操作
  // const max = props.maxNumber - 1
  inputFile.onchange = () => {
    if (props.multiply) {
      const files: FileList|[] = inputFile.files || [];
      Array.from(files).forEach((file: File) => {
        if (file.size < props.maxSize) {
          const url = windowURL.createObjectURL(file);
          if (images.value.length > 8) {
            return ElNotification.warning({
              title: "Warning",
              message: "只能选择9张图片",
              offset: 100,
            });
          } else {
            fileList.value.push(file);
            images.value.push({
              id: file.name,
              url: url,
            });
            previewList.value.push(url);
          }
        } else {
          ElNotification.warning({
            title: "Warning",
            message: `图片${file.name}大于2M`,
            offset: 100,
          });
        }
      });
      emit("upload-success", files);
    } else {
      const file:File|null = inputFile.files && inputFile.files[0];
      if (file && file?.size > 2048000) {
        return ElNotification.warning({
          title: "Warning",
          message: "图片不能大于2M",
          offset: 100,
        });
      }
      inputFileData.value = inputFile?.files?.[0] || null;
      const windowURL = window.URL || window.webkitURL; // 兼容操作
      toWindowUrl.value = windowURL.createObjectURL(inputFile?.files?.[0]);
      emit("upload-success", inputFileData.value);
      setTimeout(() => {
        inputFile = null;
      }, 200);
    }
  };
  inputFile.click();
};

const uploadImages = () => {
  const promiseList = Array.from(fileList.value).map((file: File) => {
    return uploadImageToOss(file, props.type);
  });
  
  Promise.all(promiseList)
    .then((res: any) => {
      res.forEach((result:any, index: number) => {
        if(!(result instanceof Error)) {
          setTimeout(() => {
            images.value.shift()
            fileList.value.shift()
          }, 200)
        }
      })
    })
    .catch((err: Error) => console.log(err));
};

const deletePic = () => {
  inputFileData.value = null;
  toWindowUrl.value = "";
};

const deleteMulPic = (index: number) => {
  images.value.splice(index, 1);
};
const previewPic = () => {
  dialogVisible.value = true;
};
</script>
<style lang="scss" scoped>
$picSize: 100px;
.input-picture {
  display: flex;
  align-items: center;
  font-size: 2rem;
  cursor: pointer;
  width: auto;
  height: auto;
  text-align: center;
}

.input-area {
  position: relative;
  width: $picSize;
  height: $picSize;
  img {
    position: absolute;
    width: $picSize;
    height: $picSize;
    left: 0;
  }
  .buts {
    width: 2rem;
    display: flex;
    justify-content: space-around;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    float: left;
  }
}
.el-card {
  width: 33rem;
  height: 33rem;
}

.image-list {
  width: 30rem;
  height: 30rem;
  display: grid;
  grid-template-columns: 33% 33% 33%;
  grid-template-rows: 33% 33% 33%;
  grid-gap: 5px;
  .image-container {
    position: relative;
    img {
      width: 100%;
      height: 100%;
    }
    .el-icon {
      position: absolute;
      top: 0;
      right: 0;
    }
  }
}

.input-entry {
  position: relative;
  @include flex();
  border: 1px dashed #4aa3f0;
  width: 10rem;
  height: 10rem;
  .circle-plus {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }
}
@media screen and (max-width: 768px) {
  .image-list {
    width: 100%;
    height: 100vw;
  }

  .el-card {
    width: 100%;
    height: auto;
  }
  .input-entry {
    width: 33vw;
    height: 33vw;
  }
}
</style>
